package com.xxg.curd.impl;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.xxg.curd.CurdConfig;
import com.xxg.curd.SQL;
import com.xxg.curd.SQLMap;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * 默认的全局配置实现
 */
public abstract class AbstractCurdConfigImpl implements CurdConfig {
    protected DataSource dataSource;
    protected DefaultResultFunction resultFunction = new DefaultResultFunction();

    @Override
    public DataSource getDataSource() {
        if(null == dataSource){
            ComboPooledDataSource ds = new ComboPooledDataSource();
            try {
                ds.setDriverClass(getDriver());
            } catch (PropertyVetoException e) {
                throw new RuntimeException(e);
            }
            ds.setJdbcUrl(getUrl());
            ds.setUser(getUser());
            ds.setPassword(getPassword());
            ds.setInitialPoolSize(1);
            ds.setMaxPoolSize(10);
            ds.setMaxIdleTime(10000);

            dataSource = ds;
        }

        return dataSource;
    }

    protected abstract String getPassword();

    protected abstract String getUser();

    protected abstract String getUrl();

    protected abstract String getDriver();


    @Override
    public Function<ResultSet, List<Map<String, Object>>> getResultFunction() {
        return resultFunction;
    }

    @Override
    public SQLMap getSQLMap() {
        return new SimpleSQLMap(this);
    }


    @Override
    public SQL getSQL() {
        return new BaseSQLImpl(this);
    }

    @Override
    public List<Class> getMapAnnotation() {
        return new ArrayList<>();
    }
}
